package cn.spream.jstudy.mongodb.dao.user.impl;

import com.mongodb.*;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import cn.spream.jstudy.mongodb.dao.MongoDAO;
import cn.spream.jstudy.mongodb.dao.user.UserDao;
import cn.spream.jstudy.mongodb.domain.user.User;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: cn.spream
 * Date: 12-12-3
 * Time: 上午11:27
 * To change this template use File | Settings | File Templates.
 */
public class UserDaoMongoDBImpl implements UserDao {

    private MongoDAO mongoDAO;

    @Override
    public int add(User user) {
        WriteResult writeResult = getUserCollection().save(userToDBObject(user));
        return writeResult.getN();
    }

    @Override
    public int delete(User user) {
        return getUserCollection().remove(userToDBObject(user)).getN();
    }

    @Override
    public int update(User user) {
        return getUserCollection().update(new BasicDBObject("_id", user.getId()), userToDBObject(user)).getN();
    }

    @Override
    public User getById(String id) {
        return (User) getUserCollection().findOne(new BasicDBObject("_id", new ObjectId(id)));
    }

    @Override
    public List<User> find() {
        List<User> users = new ArrayList<User>();
        DBCursor dbCursor = getUserCollection().find();
        while (dbCursor.hasNext()){
            users.add(dbObjectToUser(dbCursor.next()));
        }
        return users;
    }

    private DBObject userToDBObject(User user){
        BasicDBObject basicDBObject = new BasicDBObject();
        if(StringUtils.isNotBlank(user.getId())){
            basicDBObject.append("_id", new ObjectId(user.getId()));
        }
        basicDBObject.append("name", user.getName())
                .append("sex", user.getSex())
                .append("age", user.getAge())
                .append("mobile", user.getMobile())
                .append("address", user.getAddress());
        return basicDBObject;
    }

    private User dbObjectToUser(DBObject dbObject){
        User user = new User();
        user.setId(String.valueOf(dbObject.get("_id")));
        user.setName(String.valueOf(dbObject.get("name")));
        user.setSex(Integer.valueOf(String.valueOf(dbObject.get("sex"))));
        user.setAge(Integer.valueOf(String.valueOf(dbObject.get("age"))));
        user.setMobile(String.valueOf(dbObject.get("mobile")));
        user.setAddress(String.valueOf(dbObject.get("address")));
        return user;
    }

    private DBCollection getUserCollection(){
        return mongoDAO.getCollection(MongoDAO.CollectionType.USER);
    }

    public void setMongoDAO(MongoDAO mongoDAO) {
        this.mongoDAO = mongoDAO;
    }
}
